import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface";
import { getAuthButtonListApi, getAuthMenuListApi, getPermissionsListApi } from "@/api/modules/login";
import { getFlatMenuList, getAllBreadcrumbList, getPermissions } from "@/utils";
import { routeMenuConfig } from "@/config/route";

export const useAuthStore = defineStore({
  id: "geeker-auth",
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: {},
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: "",
    // 侧边菜单权限列表
    showMenuList: [],
    // 动态路由
    routeMenuList: [],
    permissionList: {}
  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染
    showMenuListGet: state => state.showMenuList,
    // 菜单权限列表 ==> 动态路由配置
    routeMenuListGet: state => state.routeMenuList,
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.showMenuList),
    // 权限列表 ==> 当前模块用户权限
    permissionListGet: state => state.permissionList,
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.showMenuList)
  },
  actions: {
    // Get AuthButtonList
    async getAuthButtonList() {
      const { data } = await getAuthButtonListApi();
      this.authButtonList = data;
    },
    // Get AuthMenuList
    async getAuthMenuList() {
      const { data } = await getAuthMenuListApi();
      this.authMenuList = data;
    },
    async getShowMenuList(s) {
      if (s) {
        const { data } = await getAuthMenuListApi(s);
        // this.showMenuList = data;
        this.showMenuList = data
          ? data.map(item => {
              let meta = {};
              routeMenuConfig[s].forEach(routeItem => {
                routeItem.name === item.key ? (meta = routeItem.meta) : {};
              });
              return { ...item, meta: meta };
            })
          : data;
        this.routeMenuList = routeMenuConfig[s];
      } else {
        this.showMenuList = [];
      }
    },
    async getPermissionsList(s) {
      const { data } = await getPermissionsListApi();
      this.permissionList = getPermissions(s, data);
    },
    // Set RouteName
    async setRouteName(name: string) {
      this.routeName = name;
    }
  }
});
